//
//  AccountingDetail.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import Foundation
import GRDB

struct AccountingDetail : Codable, Hashable, FetchableRecord, MutablePersistableRecord {
    var id:Int64?
    var recordId:String?
    var uid:String?
    var amount:Double?
    var date:String?
    var remark:String?
    var cid:String?
    var bookId:String?
    var createTime:String?
    var updateTime:String?
    var isDel:Int? = 0
    var dataFlag:Int? = 0
    var sv:Int? = 0
    
    enum CodingKeys: String, CodingKey {
            case id, recordId = "record_id", uid, amount, date, remark, cid, bookId = "book_id", createTime = "create_time", updateTime = "update_time", isDel = "is_del", dataFlag = "data_flag", sv
        }
    
    // 定义数据库表
    static let databaseTableName = "accounting_detail"

    enum Columns: String, ColumnExpression {
        case id, recordId = "record_id", uid, amount, date, remark, cid, bookId = "book_id", createTime = "create_time", updateTime = "update_time", isDel = "is_del", dataFlag = "data_flag", sv
    }
    
    // 实现数据库持久化方法
    mutating func didInsert(with rowID: Int64, for column: String?) {
        id = rowID
    }
    
    static func createTable(dbQueue: DatabaseQueue) {
        do {
            try dbQueue.write{ db in
                if (try db.tableExists(databaseTableName)) {
                    logger.info("table already exists \(databaseTableName)")
                } else {
                    try db.create(table: databaseTableName) { t in
                        t.autoIncrementedPrimaryKey(Columns.id.rawValue)
                        t.column(Columns.recordId.rawValue, .text)
                        t.column(Columns.uid.rawValue, .text)
                        t.column(Columns.amount.rawValue, .double)
                        t.column(Columns.date.rawValue, .text)
                        t.column(Columns.remark.rawValue, .text)
                        t.column(Columns.cid.rawValue, .text)
                        t.column(Columns.bookId.rawValue, .text)
                        t.column(Columns.createTime.rawValue, .text)
                        t.column(Columns.updateTime.rawValue, .text)
                        t.column(Columns.isDel.rawValue, .integer)
                        t.column(Columns.dataFlag.rawValue, .integer)
                        t.column(Columns.sv.rawValue, .integer)
                    }
                    try db.execute(sql: "CREATE UNIQUE INDEX unique_index_record_book_id_id_uid ON accounting_detail (record_id, book_id, uid)")
                }
            }
        } catch {
            logger.error("create accounting_detail table fail \(error)")
        }
    }
    
    mutating func update(amount: Double?, date: String?, remark: String?, cid: String?, bookId: String?) -> Bool {
        var needUpdate = false
        if self.amount != amount {
            self.amount = amount
            needUpdate = true
        }
        if self.date != date {
            self.date = date
            needUpdate = true
        }
        if self.remark != remark {
            self.remark = remark
            needUpdate = true
        }
        if self.cid != cid {
            self.cid = cid
            needUpdate = true
        }
        if self.bookId != bookId {
            self.bookId = bookId
            needUpdate = true
        }
        return needUpdate
    }
    
    mutating func makeDelete() {
        let now = Date()
        isDel = 1
        updateTime = now.toISODateString()
        dataFlag = DataFlag.update.rawValue
    }
    
    mutating func makeUpdate() {
        let now = Date()
        updateTime = now.toISODateString()
        dataFlag = DataFlag.update.rawValue
    }
}
